# _*_ coding: utf-8 _*_
from itertools import groupby
from odoo import models


class StockPicking(models.Model):
    _inherit = "stock.picking"

    def do_new_transfer_with_tolerance_check(self):
        res = super(StockPicking, self).do_new_transfer()
        for picking in self.filtered(lambda p: p.purchase_id.purchase_tolerance_id):
            line_groups = groupby(sorted(picking.purchase_id.order_line, key=lambda l: l.product_id.id),
                                  key=lambda l: l.product_id)
            for product, line_group in line_groups:
                tolerance_items = picking.purchase_id.purchase_tolerance_id.get_tolerance_items(product.id)
                if tolerance_items:
                    lines = list(line_group)
                    product_qty = sum(l.product_qty for l in lines)
                    qty_received = sum(l.qty_received for l in lines)
                    tolerance_items.check_product_qty(product_qty, qty_received, product.name_get()[0][1])
        return res
